/**
 * Description:
 * Class Name:SimpleAIOServer
 * Date:2022/5/26 14:01
 *
 * @author LTisme
 * @version JAVA17
 */
package 疯狂Java讲义.第17章_网络编程._17_3_基于TCP协议的网络编程._17_3_8_使用AIO实现非阻塞通信;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.Future;

public class SimpleAIOServer {
    static final int PORT = 30000;

    public static void main(String[] args) throws Exception{
        try (
                // 创建AsynchronousServerSocketChannel对象
                AsynchronousServerSocketChannel serverSocketChannel = AsynchronousServerSocketChannel.open()
                ){
            // 在指定地址、端口监听
            serverSocketChannel.bind(new InetSocketAddress(PORT));
            while (true){
                // 采用循环来接受来自客户端的连接请求
                Future<AsynchronousSocketChannel> future = serverSocketChannel.accept();
                // 获取连接完成后返回的AsynchronousSocketChannel
                AsynchronousSocketChannel socketChannel = future.get();
                // 执行输出
                socketChannel.write(ByteBuffer.wrap("欢迎你来到AIO世界！".getBytes(StandardCharsets.UTF_8))).get();
            }
        }
    }
}
